package com.atguigu.demo1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncLockDemo {

    //用synchronized不能中途退出,只能一直等待上一个结束占用该线程
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
        try {
            TimeUnit.SECONDS.sleep(3L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        };
        System.out.println(Thread.currentThread().getName()+"\t"+"----leave out");
    }

    //该线程被占用,直接离开,不在等待
    Lock lock = new ReentrantLock();
    public void m2(){
        if (lock.tryLock()){
            try {
                System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
                try {
                    TimeUnit.SECONDS.sleep(3L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"----leave out");
            } finally {
                lock.unlock();
            }
        }else {
            System.out.println(Thread.currentThread().getName()+"\t"+"----抢锁失败，立刻离开不等待");
        }
    }


    //在等待时间内该线程被其他线程占用结束,开始调用该线程
    //在等待时间内该线程一直被占用,直接离开,不再等待
    public void m3(){
        try {
            if (lock.tryLock(3L,TimeUnit.SECONDS)){
                try {
                    System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
                    try {
                        TimeUnit.SECONDS.sleep(2L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"\t"+"----leave out");
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SyncLockDemo syncLockDemo = new SyncLockDemo();

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                syncLockDemo.m2();
            }
        },"t1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                syncLockDemo.m2();
            }
        },"t2").start();*/

        //lambda表达式
        new Thread(() -> {
            syncLockDemo.m2();
        }, "m1").start();
        new Thread(() -> {
            syncLockDemo.m2();
        }, "m2").start();

    }
}
